package com.autonavi.yunda.yunji.service;

import com.autonavi.yunda.yunji.common.exception.AmapException;
import com.autonavi.yunda.yunji.common.exception.AmapExceptionCode;
import com.autonavi.yunda.yunji.common.utils.JsonUtils;
import com.autonavi.yunda.yunji.core.vo.EngineFunctionConfigVO;
import com.autonavi.yunda.yunji.core.vo.EngineInterfaceConfigVO;
import com.autonavi.yunda.yunji.core.vo.localization.DatasourceExportVO;
import com.autonavi.yunda.yunji.core.vo.localization.DynamicExportVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @description 文件加载服务
 * @author <a href="mailto:yanxudong.yxd@alibaba-inc.com">Send Email 2 阎旭东(观清)</a>
 * @date 2023/9/12
 * @version 1.0
 */
@Slf4j
@Component
public class FileLoaderService {
    protected static List<EngineInterfaceConfigVO> interfaceConfigVOS = new ArrayList<>();
    protected static List<DatasourceExportVO> datasourceConfigVOS = new ArrayList<>();
    protected static List<DynamicExportVO> dynamicConfigVOS = new ArrayList<>();
    protected static List<EngineFunctionConfigVO> functionConfigVOS = new ArrayList<>();
    @Value("${project.path:/tmp/data}")
    private String filePath;

    /**
     * 初始化接口配置
     */
    @PostConstruct
    private void init() {
        try {
            filePath = filePath.endsWith("/") ? filePath : filePath + "/";

            interfaceConfigVOS = readFilesFromFolder(filePath, "interface").stream()
                    .map(interfaceConfig -> JsonUtils.from(interfaceConfig, EngineInterfaceConfigVO.class))
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            datasourceConfigVOS = readFilesFromFolder(filePath, "datasource").stream()
                    .map(datasource -> JsonUtils.from(datasource, DatasourceExportVO.class))
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            dynamicConfigVOS = readFilesFromFolder(filePath, "dynamic").stream()
                    .map(dynamic -> JsonUtils.from(dynamic, DynamicExportVO.class))
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            functionConfigVOS = readFilesFromFolder(filePath, "function").stream()
                    .map(function -> JsonUtils.from(function, EngineFunctionConfigVO.class))
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("init interface config error", e);
        }
    }

    /**
     * 读取需加载的资源信息内容
     * @param folderPath    文件夹路径
     * @return              资源信息列表
     */
    public List<String> readFilesFromFolder(String folderPath, String type) {
        List<String> fileContents = new ArrayList<>();

        // 读取指定类型的文件目录
        File folder = new File(folderPath + type);
        if (!folder.exists()) {
            throw new AmapException(AmapExceptionCode.COMMON_SERVER_ERROR, "读取" + type + "文件失败,请检查目录是否正确:" + folderPath);
        }

        File[] fileList = folder.listFiles();
        if (fileList != null && fileList.length > 0) {
            fileContents = Arrays.stream(fileList).map(this::readFile).collect(Collectors.toList());
        }
        return fileContents;
    }

    /**
     * 读取文件内容
     * @param file  文件
     * @return  文件内容
     */
    private String readFile(File file) {
        if (!file.exists()) {
            throw new AmapException(AmapExceptionCode.COMMON_SERVER_ERROR, "读取文件失败,请检查文件是否存在");
        }
        // 读取每个子文件的内容
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
        } catch (IOException e) {
            throw new AmapException(AmapExceptionCode.COMMON_SERVER_ERROR, "读取文件失败,IO异常", e);
        }
        return content.toString();
    }

}
